package com.aps.apspda.activity;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aps.apspda.R;
import com.aps.apspda.adapter.EqpThingListAdapter;
import com.aps.apspda.base.BaseActivity;
import com.aps.apspda.callback.DeleteCallback;
import com.aps.apspda.callback.DialogEntityCallBack;
import com.aps.apspda.callback.EntityCallBack;
import com.aps.apspda.dialog.WarnFragmentDialog;
import com.aps.apspda.entity.BaseEntity;
import com.aps.apspda.entity.FinishLotEntity;
import com.aps.apspda.entity.MaterialInfo2Entity;
import com.aps.apspda.entity.MaterialInfoBean;
import com.aps.apspda.entity.NewEqpEntity;
import com.aps.apspda.myview.TitleView;
import com.aps.apspda.utils.AntiShake;
import com.aps.apspda.utils.NetUtils;
import com.aps.apspda.utils.StaticMembers;
import com.aps.apspda.utils.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class ThingChangeListActivity extends BaseActivity {

    @BindView(R.id.topView)
    TitleView topView;
    @BindView(R.id.tvEqpId)
    TextView tvEqpId;
    @BindView(R.id.rvEqpList)
    RecyclerView rvEqpList;
    @BindView(R.id.btnChange)
    Button btnChange;
    /*    @BindView(R.id.btnrefillepoxy)
        Button btnrefillepoxy;*/
    private EqpThingListAdapter eqpThingListAdapter;
    private String eid;
    private String eqptype;//2019-9-20 新增加全局变量
    private String opid;//2019-9-20 新增加全局变量
    private String lotid;//2019-9-20 新增加全局变量
    private String modeselsecttype;
    private Handler mHandler = new Handler();
    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            ThingChangeListActivity.this.finish();
        }
    };
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // 将返回值回调到callBack的参数中
            switch (msg.what) {
                case 0:
                    requestData();
                    break;
            }
        }
    };
    private List<MaterialInfoBean> materialInfoBeanList;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_thing_change_list;
    }

    @Override
    protected void initView() {
        topView.setTitle("材料列表(" + StaticMembers.CUR_USER.getUSERNAME() + ")");
        rvEqpList.setLayoutManager(new LinearLayoutManager(ThingChangeListActivity.this));
        rvEqpList.setItemAnimator(new DefaultItemAnimator());
        rvEqpList.addItemDecoration(new DividerItemDecoration(ThingChangeListActivity.this, 1));
    }
    //modify by bunny  弹框点击确认后页面再回主界面
    private void showdailog(String message) {
        final WarnFragmentDialog dialog = new WarnFragmentDialog();
        dialog.setData(message);
        dialog.setListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                mHandler.postDelayed(runnable, 100);
            }
        });
        dialog.show(getSupportFragmentManager(), "check_fail_tips");
    }
    @Override
    protected void initData() {
        eid = getIntent().getStringExtra("eqpID");
        eqptype = getIntent().getStringExtra("eqpType");
        if(eqptype==null )
        {
            EntityCallBack<BaseEntity<NewEqpEntity>> callBack = new DialogEntityCallBack<BaseEntity<NewEqpEntity>>
                    (new TypeToken<BaseEntity<NewEqpEntity>>() {
                    }.getType(), getSupportFragmentManager(), this) {

                @Override
                public void onSuccess
                        (final Response<BaseEntity<NewEqpEntity>> response) {
                    if (response.body().isSuccess(ThingChangeListActivity.this)) {
                        eqptype = response.body().getData().getEQPINFOLIST().getEQPINFO().get(0).getEQPTYPE();
                    } else {
                        showdailog(response.body().getMessage());
                    }
                }

                @Override
                public void onError
                        (Response<BaseEntity<NewEqpEntity>> response) {
                    super.onError(response);
                    loadError(response.getException(), "ShowReserveEQPInfoC2E");
                }
            };

            Map<String, String> map = new HashMap<>();
            map.put("EQPID", getEqpID());
            map.put("USERNAME", StaticMembers.CUR_USER.getUSERNAME());
            NetUtils.requestNet(this, "/ShowReserveEQPInfoC2E", map, callBack);
        }
        //opid = getIntent().getStringExtra("opid");
        opid = StaticMembers.CUR_USER.getUSERNAME();
        lotid = getIntent().getStringExtra("lotId");
        modeselsecttype = getIntent().getStringExtra("modeselsecttype");
        if ("FE-DFN-ASMDB".equals(eqptype) || "FE-SMDE-ASMDB".equals(eqptype)||"FE-Power-ASMDB".equals(eqptype)) {
            View weiget = findViewById(R.id.btnleadframe);
            View weiget1 = findViewById(R.id.btndisk);
            View weiget2 = findViewById(R.id.btndummyLF);
            View weiget3 = findViewById(R.id.btnrefillepoxy);
            LinearLayout linearLayout = findViewById(R.id.linearLayout);
            weiget.setVisibility(View.VISIBLE);//按钮显示
            weiget1.setVisibility(View.VISIBLE);//按钮显示
            weiget2.setVisibility(View.VISIBLE);//按钮显示
            weiget3.setVisibility(View.VISIBLE);//按钮显示
            linearLayout.setVisibility(View.VISIBLE); // 显示

        } else {
            View weiget = findViewById(R.id.btnleadframe);
            View weiget1 = findViewById(R.id.btndisk);
            View weiget2 = findViewById(R.id.btndummyLF);
            View weiget3 = findViewById(R.id.btnrefillepoxy);
            LinearLayout linearLayout = findViewById(R.id.linearLayout);
            weiget.setVisibility(View.GONE);//按钮隐藏
            weiget1.setVisibility(View.GONE);//按钮隐藏
            weiget2.setVisibility(View.GONE);//按钮隐藏
            weiget3.setVisibility(View.GONE);//按钮隐藏
            linearLayout.setVisibility(View.GONE); // 隐藏
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mHandler.removeCallbacks(runnable);
        OkGo.getInstance().cancelTag(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        requestData();
    }

    private void requestData() {
        EntityCallBack<BaseEntity<MaterialInfo2Entity>> callBack = new DialogEntityCallBack<BaseEntity<MaterialInfo2Entity>>
                (new TypeToken<BaseEntity<MaterialInfo2Entity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<MaterialInfo2Entity>> response) {
                if (response.body().isSuccess(ThingChangeListActivity.this)) {
                    tvEqpId.setText(response.body().getData().getEqpId());
                    if (response.body().getData().getMaterials().getMesMaterial().size() == 0) {
                        loadFail("该设备没有设置BOM,请联系相关人员");
                    }
                    if (response.body().getData().getMaterials().getMesMaterial().size() == 2 &&
                            response.body().getData().getMaterials().getMesMaterial().get(0).getType().toLowerCase().contains("hubblade")
                            && response.body().getData().getMaterials().getMesMaterial().get(1).getType().toLowerCase().contains("hubblade")) {
                        btnChange.setVisibility(View.VISIBLE);
                        materialInfoBeanList = response.body().getData().getMaterials().getMesMaterial();
                    } else {
                        btnChange.setVisibility(View.GONE);
                    }
            /*        if(("FE-Power-ASMDB").equals(eqptype)){
                        for(MaterialInfoBean materialInfoBean:response.body().getData().getMaterials().getMesMaterial()){
                            if(materialInfoBean.getType().equals("Leadframe")){
                                materialInfoBean.setEqpType(eqptype);
                            }
                        }
                    }*/
                    eqpThingListAdapter = new EqpThingListAdapter(response.body().getData().getMaterials().getMesMaterial(),
                            new DeleteCallback() {
                        @Override
                        public void onSuccess(MaterialInfoBean bean) {
                            final EntityCallBack<BaseEntity<FinishLotEntity>> callBack = new DialogEntityCallBack<BaseEntity<FinishLotEntity>>
                                    (new TypeToken<BaseEntity<FinishLotEntity>>() {
                                    }.getType(), getSupportFragmentManager(), this) {

                                @Override
                                public void onSuccess
                                        (final Response<BaseEntity<FinishLotEntity>> response) {
                                    if (response.body().isSuccess(ThingChangeListActivity.this)) {
                                        requestData();
                                        loadSuccess(response.body().getMessage());
                                    } else {
                                        loadFail(response.body().getMessage());
                                    }
                                }

                                @Override
                                public void onError
                                        (Response<BaseEntity<FinishLotEntity>> response) {
                                    super.onError(response);
                                    loadError(response.getException(), "UnloadEQPMeterial");
                                }
                            };

                            Map<String, String> map = new HashMap<>();
                            map.put("EqpId", getEqpID());
                            map.put("MaterialPartNo", bean.getMaterialPartNo());
                            map.put("OPID", StaticMembers.CUR_USER.getUSERNAME());
                            map.put("Type", bean.getType());
                            map.put("SeqNo", bean.getSeqNo());
                            NetUtils.requestNet(this, "/UnloadEQPMeterial", map, callBack);
                        }
                    });
                  /*           if(("FE-Power-ASMDB").equals(eqptype)){
                                 MaterialInfoBean materialInfoBean = new MaterialInfoBean();
                                 materialInfoBean.setEqpType(eqptype);
                                 eqpThingListAdapter.getData().add(materialInfoBean);
                    }*/
                    eqpThingListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
                    eqpThingListAdapter.setFragmentManager(getSupportFragmentManager());
                    eqpThingListAdapter.isFirstOnly(true);
                    rvEqpList.setAdapter(eqpThingListAdapter);
                } else {
                    loadFail(response.body().getMessage());
                    mHandler.postDelayed(runnable, 1000);
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<MaterialInfo2Entity>> response) {
                super.onError(response);
                loadError(response.getException(), "ShowMeterial");
                mHandler.postDelayed(runnable, 1000);
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("EqpId", eid);
        NetUtils.requestNet(this, "/ShowMeterial", map, callBack);
    }

    /*2019-9-19新增  Start*/
    EntityCallBack<BaseEntity<FinishLotEntity>> callBack = new DialogEntityCallBack<BaseEntity<FinishLotEntity>>
            (new TypeToken<BaseEntity<FinishLotEntity>>() {
            }.getType(), getSupportFragmentManager(), this) {

        @Override
        public void onSuccess
                (final Response<BaseEntity<FinishLotEntity>> response) {
            if (response.body().isSuccess(ThingChangeListActivity.this)) {
                Message message = new Message();
                message.what = 0;
                handler.sendMessage(message);
                if (response != null && response.body() != null && response.code() == 200) {
                    response.body().setMessage("更换成功!");
                    loadSuccess(response.body().getMessage());
                } else {
                    response.body().setMessage("更换异常!");
                    loadSuccess(response.body().getMessage());
                }
            } else {
                loadFail(response.body().getMessage());
            }
        }

        /*2019-9-20 新增 End*/
        @Override
        public void onError
        (Response<BaseEntity<FinishLotEntity>> response) {
            super.onError(response);
            loadError(response.getException(), "ReplaceMaterial");
        }
    };

    @OnClick({R.id.btnChange, R.id.btnleadframe, R.id.btndisk, R.id.btndummyLF, R.id.btnrefillepoxy})
    public void onClick(final View view) {
        if (AntiShake.check(view.getId())) {    //判断是否多次点击
            ToastUtils.showFreeToast("请勿重复点击",
                    ThingChangeListActivity.this, false, Toast.LENGTH_SHORT);
            return;
        }
        switch (view.getId()) {
            case R.id.btnChange:
                Intent intent = new Intent(this, BothThingChangeActivity.class);
                intent.putExtra("mEntity1", materialInfoBeanList.get(0));
                intent.putExtra("mEntity2", materialInfoBeanList.get(1));
                intent.putExtra("eqpID", getEqpID());
                intent.putExtra("eqpType", eqptype);
                intent.putExtra("numIs","0");
                startActivity(intent);
                break;
            //更换框架
            case R.id.btnleadframe:
                AlertDialog.Builder dialog = new AlertDialog.Builder(ThingChangeListActivity.this);
                dialog.setMessage("确定添加框架?");
                dialog.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Map<String, String> map = new HashMap<>();
                        map.put("EQPID", eid);
                        map.put("OPID", StaticMembers.CUR_USER.getUSERNAME());
                        map.put("MATERIALTYPE", "LEADFRAME");
                        map.put("LOTID", lotid);
                        NetUtils.requestNet(this, "/ReplaceMaterial", map, callBack);
                    }
                });
                dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                });
                dialog.show();
                break;
            //更换胶盘
            case R.id.btndisk:
                AlertDialog.Builder builder = new AlertDialog.Builder(ThingChangeListActivity.this);
                builder.setMessage("确定更换胶盘?");
                builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Map<String, String> map = new HashMap<>();
                        map.put("EQPID", eid);
                        map.put("OPID", StaticMembers.CUR_USER.getUSERNAME());
                        map.put("MATERIALTYPE", "DISK");
                        map.put("LOTID", lotid);
                        NetUtils.requestNet(this, "/ReplaceMaterial", map, callBack);
                    }
                });
                builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                });
                builder.show();
                break;
            //新增测试片
            case R.id.btndummyLF:
                AlertDialog.Builder builderLf = new AlertDialog.Builder(ThingChangeListActivity.this);
                builderLf.setMessage("确定打测试片?");
                builderLf.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Map<String, String> map = new HashMap<>();
                        map.put("EQPID", eid);
                        map.put("OPID", StaticMembers.CUR_USER.getUSERNAME());
                        map.put("MATERIALTYPE", "DUMMYLF");
                        map.put("LOTID", lotid);
                        NetUtils.requestNet(this, "/ReplaceMaterial", map, callBack);
                    }
                });
                builderLf.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                    }
                });
                builderLf.show();
                break;
            //加胶
            case R.id.btnrefillepoxy:
                      /*  AlertDialog.Builder buildepoxy = new AlertDialog.Builder(ThingChangeListActivity.this);
                        buildepoxy.setIcon(R.drawable.ic_launcher_background);
                        buildepoxy.setTitle("");
                        //通过LayoutInflater来加载一个xml的布局文件作为一个View对象
                        View view1 = LayoutInflater.from(ThingChangeListActivity.this).inflate(R.layout.activity_epoxy, null);
                        //    设置我们自己定义的布局文件作为弹出框的Content
                        buildepoxy.setView(view1);
                        final EditText epoxyno = (EditText) view1.findViewById(R.id.btnepoxyno);
                        final EditText block = (EditText) view1.findViewById(R.id.btnblock);
                        final EditText sliceno = (EditText) view1.findViewById(R.id.btnsliceno);

                        buildepoxy.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                if (epoxyno.getText().toString().trim().length() == 0) {
                                    ToastUtils.showFreeToast("请输入银浆批次号", ThingChangeListActivity.this, false, Toast.LENGTH_SHORT);
                                    return;
                                }
                                if (block.getText().toString().trim().length() == 0) {
                                    ToastUtils.showFreeToast("请输入Block", ThingChangeListActivity.this, false, Toast.LENGTH_SHORT);
                                    return;
                                }
                                if (sliceno.getText().toString().trim().length() == 0) {
                                    ToastUtils.showFreeToast("请输入片号", ThingChangeListActivity.this, false, Toast.LENGTH_SHORT);
                                    return;
                                }
                                Map<String, String> map = new HashMap<>();
                                map.put("EQPID", eid);
                                map.put("OPID", StaticMembers.CUR_USER.getUSERNAME());
                                map.put("MATERIALTYPE", "REFILLEPOXY");
                                map.put("LOTID", lotid);
                                map.put("EPOXYNO", epoxyno.getText().toString().trim());
                                map.put("BLOCK", block.getText().toString().trim());
                                map.put("SLICENO", sliceno.getText().toString().trim());
                                NetUtils.requestNet(this, "/ReplaceMaterial", map, callBack);
                            }
                        });
                        buildepoxy.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                            }
                        });
                        buildepoxy.show();*/
                //创建输入框
                //通过LayoutInflater来加载一个xml的布局文件作为一个View对象
                View view1 = LayoutInflater.from(ThingChangeListActivity.this).inflate(R.layout.activity_epoxy, null);
                final AlertDialog buildepoxy = new AlertDialog.Builder(ThingChangeListActivity.this)
                        .setView(view1)
                        .setPositiveButton("保存", null)
                        .setNegativeButton("取消", null)
                        .show();
                buildepoxy.setView(view1);
                final EditText epoxyno = (EditText) view1.findViewById(R.id.btnepoxyno);
                final EditText block = (EditText) view1.findViewById(R.id.btnblock);
                final EditText sliceno = (EditText) view1.findViewById(R.id.btnsliceno);
                block.setInputType( InputType.TYPE_CLASS_NUMBER);
                sliceno.setInputType( InputType.TYPE_CLASS_NUMBER);
                (buildepoxy).getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view1) {
                        if (epoxyno.getText().toString().trim().length() == 0) {
                            ToastUtils.showFreeToast("请输入银浆批次号", ThingChangeListActivity.this, false, Toast.LENGTH_SHORT);
                            return;
                        } else if (block.getText().toString().trim().length() == 0) {
                            ToastUtils.showFreeToast("请输入Block", ThingChangeListActivity.this, false, Toast.LENGTH_SHORT);
                            return;
                        } else if (sliceno.getText().toString().trim().length() == 0) {
                            ToastUtils.showFreeToast("请输入片号", ThingChangeListActivity.this, false, Toast.LENGTH_SHORT);
                            return;
                        }else if(block.getText().toString().substring(0,1).equals("0")){
                            ToastUtils.showFreeToast("Block首位不能是0", ThingChangeListActivity.this, false, Toast.LENGTH_SHORT);
                            return;
                        }else if(sliceno.getText().toString().substring(0,1).equals("0")){
                            ToastUtils.showFreeToast("片号首位不能是0", ThingChangeListActivity.this, false, Toast.LENGTH_SHORT);
                            return;
                        } else if(Integer.parseInt(block.getText().toString())<=0){
                            ToastUtils.showFreeToast("Block请输入大于0的整数", ThingChangeListActivity.this, false, Toast.LENGTH_SHORT);
                            return;
                        }else if(Integer.parseInt(sliceno.getText().toString())<=0){
                            ToastUtils.showFreeToast("片号请输入大于0的整数", ThingChangeListActivity.this, false, Toast.LENGTH_SHORT);
                            return;
                        }else{
                            Map<String, String> map = new HashMap<>();
                            map.put("EPOXYNO", epoxyno.getText().toString());
                            map.put("BLOCK", block.getText().toString());
                            map.put("SLICENO", sliceno.getText().toString());
                            map.put("EQPID", eid);
                            map.put("OPID", StaticMembers.CUR_USER.getUSERNAME());
                            map.put("MATERIALTYPE", "REFILLEPOXY");
                            map.put("LOTID", lotid);
                            NetUtils.requestNet(this, "/ReplaceMaterial", map, callBack);
                            buildepoxy.cancel();
                        }
                    }
                });
                (buildepoxy).getButton(AlertDialog.BUTTON_NEGATIVE).setOnClickListener(new View.OnClickListener() {
                    public void onClick(View view1) {
                        buildepoxy.cancel();
                    }
                });
                buildepoxy.show();
                break;
        }

    }
}
